<template>
  <div id="app">
    <h1>cart</h1>
    <List
      :goodsList="goodsList"
      :amount="amount"
      :total="total"
      @countChange="onGoodsCountChange"
      @handleDelChange="handleDelChange"
      @listChange="listChange"
    />
  </div>
</template>

<script>
import List from '@/components/List.vue';
export default {
  name: 'App',
  components: { List },
  data() {
    return {
      goodsList: [
        { id: 1, name: 'Chicken Wing', category: 'Food', qty: 3, price: 10 },
        { id: 2, name: 'Pizza', category: 'Food', qty: 1, price: 50 },
        { id: 3, name: 'Hamburger', category: 'Food', qty: 1, price: 12 },
        { id: 4, name: 'Coca Cola', category: 'Drink', qty: 2, price: 5 },
        { id: 5, name: 'Orange Juice', category: 'Drink', qty: 1, price: 15 },
        { id: 6, name: 'Potato Chips', category: 'Snack', qty: 1, price: 8 },
      ],
    };
  },
  methods: {
    // 监听数量变化
    onGoodsCountChange(value) {
      // console.log('value', value); //{}
      this.goodsList.forEach((item) => {
        if (item.id == value.id) {
          item.qty = value.val;
        }
      });
    },
    // 删除
    handleDelChange(id) {
      console.log('del', id);
      this.goodsList = this.goodsList.filter((item) => item.id !== id);
    },
    listChange(data) {
      this.goodsList = data;
    },
  },
  computed: {
    // 商品的总价格
    amount() {
      let sum = 0;
      this.goodsList.forEach((item) => {
        sum += item.price * item.qty;
      });
      return sum;
    },
    //  商品的总数量
    total() {
      let sum = 0;
      this.goodsList.forEach((item) => {
        sum += item.qty;
      });
      return sum;
    },
  },
};
</script>

<style lang="scss">
#app {
  max-width: 1200px;
  margin: 0 auto;
}
</style>
